const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const jsonrpcServer = require('./kitties/lab/library/jsonrpc-server.js');
const session = require('express-session');
const indexRouter = require('./routes/index.js');
const app = express();
require('./kitties/lab/index.js');
const rootURL = "/gateway/api/jsonrpc.jsp";

// view engine setup
app.set('views', path.join(__dirname, 'ui-frontend/build'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

app.use(express.static(path.join(__dirname, 'ui-frontend/build/static')));


app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(session({
    "name" : "HaMSID",
    "secret" : "secret", 
    "resave" : false,
    "saveUninitialized" : false,
    "cookie" : {
        "secure" : false,
        "httpOnly": true,
        "maxAge" : 1000 * 60 * 60 * 24 * 7 , 
    },
    "genid" : ()=> {
        return $.uuid()
    }
}));
//application/json
app.use(bodyParser.json()); 

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    let uri = req.params['0'] ? req.params['0'] : '/' ;
    $info(`${req.method} ${uri}`);
    next()
})

app.use('/',indexRouter);

// config jsonrpc server
app.use(rootURL,jsonrpcServer);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
